//
//  HMService.swift
//  home
//
//  Created by Yun Zeng on 2018/11/25.
//  Copyright © 2018 Yun Zeng. All rights reserved.
//

import Foundation

// 服务类型
enum HMServiceType: String, Codable {
    case unknown = "0"
    
    case accessoryInformation = "1"
    case accessoryBridge = "2"
    case accessoryDFU = "3"
    
    case contactSensor = "11"       // 接触式传感器，如: 门磁
    case htSensor = "12"
    case lightSensor = "13"
    case outlet = "14"
    case `switch` = "15"
    case airConditioner = "16"      // 空调
    case clock = "17"               // 闹钟
    case colorLight = "18"          // 彩色灯
    case temperatureColorLight  = "19"  // 色温灯
    case zigbeeCoordinator = "20"       // Zigbee 协调器
    case motion = "21"                  // 人体运动检测
    case button = "23"          // 情景按键
}

// 配件的服务
// 服务是交互控制的基本单元，也是自动化，场景执行的基本单元
// 用户的所有操作都围绕服务进行
class HMService: Codable {
    
    // 指向服务所有的配件
    var accessory: HMAccessory?
    
    // 指向用户层服务
    var surface: Service?
    
    // 服务描述
    var id: Int
    var type: HMServiceType {
        set {
            self._type = newValue.rawValue
        }
        get {
            if let t = HMServiceType(rawValue: self._type) {
                return t
            }
            return .unknown
        }
    }
    var characteristics: [HMCharacteristic]
    
    // JSON格式输出
    var _type: String = HMServiceType.unknown.rawValue
    private enum CodingKeys: String, CodingKey {
        case id = "sid"
        case _type = "type"
        case characteristics
    }
    
    init(id: Int = 0, type: HMServiceType, characteristics: [HMCharacteristic]) {
        self.id = id
        self.characteristics = characteristics
        self.type = type
    }
    
    func needUpdate(state: Service.State) {
        self.surface?.state = state
    }
}

// 调试打印输出
extension HMService: CustomStringConvertible {
    var description: String {
        let data = try! JSONEncoder().encode(self)
        return String(data: data, encoding: .utf8)!
    }
}

// 查找功能
extension HMService {
    func findCharacteristic(type: HMCharacteristicType) -> HMCharacteristic? {
        for characteristic in self.characteristics {
            if characteristic.type == type {
                return characteristic
            }
        }
        return nil
    }
    
    func findCharacteristic(id: Int) -> HMCharacteristic? {
        for characteristic in self.characteristics {
            if characteristic.id == id {
                return characteristic
            }
        }
        return nil
    }
}




